//
//  RequestHttpTool.swift
//  SXH_SwiftProject
//
//  Created by 孙先华 on 2019/6/21.
//  Copyright © 2019 سچچچچچچ. All rights reserved.

import Foundation
import UIKit

import Alamofire
import HandyJSON

import SVProgressHUD

///  网络请求
class RequestHttpTool{
    
    
    var successBlock :((NSDictionary)->Void)?
    var faileBlock :((String?)->Void)?

    init(){}
    //普通网络请求
    public func request(method :HTTPMethod = .post, url :String,parameters: [String: AnyObject]?, successCallBack: @escaping ((NSDictionary) ->()),failCallBack: ((String?)->())?){
        
        self.successBlock = successCallBack
        self.faileBlock   = failCallBack
        let dic :[String:Any]? = parameters
        Alamofire.request(url, method: .get, parameters: dic, encoding:JSONEncoding.default).responseJSON {[weak self] (returnResponse) in
            
            switch returnResponse.result {
            case .success(let value):
                
                guard let dic = value as? NSDictionary else {
                    self?.faillHandle()
                    return
                }
                
                //获取并判断 返回码
                guard let status = dic["status"] as? String else {
                    failCallBack?("请求失败")
                    return
                }
                if status == "ok" {
                    successCallBack(dic)
                }else{
                    failCallBack?("请求失败")
                }
                
            case .failure(let error):
                
                self?.faillHandle(error: error)
                
                debugPrint(" ---------------- 通 讯 失 败 ---------------- ")
//                HUD.showTip(error.localizedDescription) {
//                    failCallBack?("error")
//                }

            }
            
        }
        
    }
    
    
    func faillHandle(error :Error? = nil,dic :NSDictionary? = nil){
        
        if error != nil {
            self.faileBlock?(error?.localizedDescription)
            return
        }
        
    }

    
    
    
}


